from typing import Self

import phonenumbers
from phonenumbers import NumberParseException
from pydantic import Field, model_validator, field_validator, EmailStr

from .base import Base
from .resume_id import ResumeContactId


class BaseResumeContact(Base):
    email: EmailStr | None = Field(None, description='E-mail')
    phone: str | None = Field(None, description='Номер телефона')
    telegram: str | None = Field(None, description='Telegram')

    @field_validator('telegram')
    @classmethod
    def valid_telegram(cls, telegram: str | None) -> str | None:
        if telegram is None:
            return telegram
        if telegram[0] != '@':
            raise ValueError('Введен неверный username!')
        return telegram

    @field_validator('phone')
    @classmethod
    def valid_phone(cls, phone: str | None) -> str | None:
        if phone is None:
            return phone
        msg = 'Номер телефона введен неверно!'
        try:
            number = phonenumbers.parse(phone, None)
        except NumberParseException:
            raise ValueError(msg)
        if not phonenumbers.is_possible_number(number):
            raise ValueError(msg)
        return phone


class ResumeContactCreate(BaseResumeContact):
    @model_validator(mode='after')
    def check_fields(self) -> Self:
        if not any((self.email, self.phone, self.telegram)):
            raise ValueError('Должно быть заполнено одно из полей!')
        return self


class ResumeContactResult(BaseResumeContact):
    id: ResumeContactId = Field(
        ...,
        description='Уникальный идентификатор пользователя'
    )


class ResumeContactUpdate(BaseResumeContact):
    pass
